<script lang="ts" setup>
import type { DataType } from './types';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, Input, message, Modal, Space, Switch } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getMsgTemplate,
  postMsgTemplateStatus,
  postMsgTemplateTest,
} from '#/api/plugin/wechat';
import Icon from '#/components/Icons';
import { toggleStatus } from '#/utils';

import { FormModalView } from './components';

defineOptions({
  name: 'PluginWechatAdminIndexmsgTemplate',
});
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');

const state = reactive({
  testForm: {
    id: 0,
    openid: '',
  },
});
const openid = ref('');
const isupdate = ref(0);
const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: [
    { field: 'title', title: '模板标题' },
    { field: 'template_id', title: '模板ID' },
    { field: 'primary_industry', title: '所属行业(一级)' },
    {
      field: 'deputy_industry',
      title: '所属行业(二级)',
    },
    { field: 'content', title: '模板内容' },
    { field: 'example', title: '模板示例' },
    { field: 'status', title: '状态', slots: { default: 'status' } },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const { data } = await getMsgTemplate({
          page: page.currentPage,
          limit: page.pageSize,
          isupdate: isupdate.value,
        }).finally(() => {
          isupdate.value = 0;
        });
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const onChange = async (row: DataType) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要${row.status === 0 ? '停用' : '启用'}吗?`,
    async onOk() {
      try {
        await postMsgTemplateStatus(row);
        message.success(`已${row.status === 0 ? '停用' : '启用'}`);
      } catch {
        row.status = toggleStatus(row.status);
      }
    },
    onCancel() {
      row.status = toggleStatus(row.status);
    },
  });
};

const [FormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});

const handleUpdate = async () => {
  isupdate.value = 1;
  GridApi.query();
};

const openDialog = async (title: '新增' | '编辑', row?: DataType | null) => {
  formModalApi.setState({
    title: `${title}${viewTitle}`,
  });
  formModalApi.setData(row);
  formModalApi.open();
};

const [TestModal, modalApi] = useVbenModal({
  onConfirm: async () => {
    state.testForm.openid = openid.value;
    if (!state.testForm.openid) {
      message.error('请输入Openid');
      return;
    }
    await postMsgTemplateTest(state.testForm);
    message.success('发送成功');
    modalApi.close();
  },
});

const handleSend = (id: number) => {
  state.testForm.id = id;
  modalApi.open();
};
</script>

<template>
  <Page auto-content-height>
    <FormModal />
    <TestModal class="w-[600px]" title="发送测试">
      <Input v-model:value="openid" />
    </TestModal>
    <Grid :table-title="`${viewTitle}列表`">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="handleUpdate">
          <span class="anticon">
            <Icon icon="ri:refresh-line" />
          </span>
          同步{{ viewTitle }}
        </Button>
      </template>
      <template #status="{ row }">
        <Switch
          v-model:checked="row.status"
          :checked-value="1"
          :un-checked-value="0"
          checked-children="启用"
          un-checked-children="停用"
          @change="onChange(row)"
        />
      </template>

      <template #action="{ row }">
        <Space>
          <Button
            :disabled="row.status === 0"
            type="primary"
            @click="openDialog('编辑', row)"
          >
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            编辑
          </Button>
          <Button
            :disabled="row.status === 0"
            type="primary"
            @click="handleSend(row.id)"
          >
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:send-plane-line" />
              </span>
            </template>
            测试
          </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
